<template>
  <view class="kaptcha-container" :style="{border: border}">
    <!-- <view class="item-title">图文验证</view> -->
    <input
      class="u-m-r-10 u-flex-1"
      type="text"
      v-model="twInput"
      placeholder="请输入图文验证码"
			@input="changeInput"
    ></input>
    <image
      style="width: 200rpx; height: 40rpx"
      :src="twYZM"
      mode="widthFix"
      @click="getKaptcha"
      alt="图文验证码"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted,defineEmits, defineExpose } from 'vue';
import { baseURL } from '../../utils/base_url';


const emit = defineEmits(['change']);
// 验证码输入框的值
const twInput = ref<string>('');

// 验证码图片的 URL
const twYZM = ref<string>('');

// 获取验证码的方法
const getKaptcha = async () => {
  try {
		uni.request({
        url: baseURL + "/api/sms/kaptcha",
        method: "POST",
        responseType: "arraybuffer", // 将 responseType 放在正确的位置
        success: (response: any) => {
          const base64 = uni.arrayBufferToBase64(response.data);
          const imageUrl = "data:image/jpeg;base64," + base64;
          twYZM.value = imageUrl;
        },
      });
  } catch (error) {

  }
};

const changeInput = (e: any) => {
	emit('change', e.detail.value);
};

// 组件挂载时获取初始验证码
onMounted(() => {
  getKaptcha();
});

const reset = () => {
  twInput.value = "";
  getKaptcha();
};

// 暴露方法供父组件调用
defineExpose({
  reset
});

</script>

<style scoped>
.kaptcha-container {
  display: flex;
  align-items: center;
}

.item-title {
  font-size: 16px;
  margin-right: 10px;
}

.u-m-r-10 {
  margin-right: 10px;
}

.u-flex-1 {
  flex: 1;
}
</style>